<script setup lang="ts">
import { defineAsyncComponent, nextTick, ref, unref } from 'vue'
import type { BusinessUIAction, BusinessUIFormType, DicType } from '@/types/custom'
import { clone } from 'xe-utils'
import { Edit } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus'

const TemplateGrid = defineAsyncComponent(() => import('@/views/components/grid/TemplateGrid.vue'))
const TemplatePrint = defineAsyncComponent(
  () => import('@/views/components/grid/components/TemplatePrint.vue')
)
const TemplateOvertime = defineAsyncComponent(
  () => import('@/views/components/grid/components/TemplateOvertime.vue')
)
const TemplateDeduction = defineAsyncComponent(
  () => import('@/views/components/grid/components/TemplateDeduction.vue')
)
const TemplateFormContent = defineAsyncComponent(
  () => import('@/views/components/form/components/TemplateFormContent.vue')
)
const TemplateTableSelector = defineAsyncComponent(
  () => import('@/views/components/grid/components/TemplateTableSelector.vue')
)

interface Props {
  modal?: boolean
  disabled?: boolean
  params?: TypedAny
  uiForm?: BusinessUIFormType
  dicTable?: DicType[]
  // 全局参数
  id?: string
  title?: string
  action?: BusinessUIAction
  row?: TypedAny
}

defineProps<Props>()

const emit = defineEmits(['fetch', 'submit'])

const _id = ref('')
const _key = ref('')
const _page = ref()
const _edit = ref(false)
const _title = ref('')
const _row = ref<TypedAny | undefined>()
// 按钮参数
const _params = ref<TypedAny>({})
const _action = ref<BusinessUIAction | undefined>()
const _loading = ref(false)
const _edit_keys = ['TemplateDeduction', 'TemplateOvertime', 'TemplateForm']
const fullscreen = ref(false)
const dialogVisible = ref(false)
const _business = ref<string | undefined>()

const open = (key: string, data: Props) => {
  _id.value = data.id || ''
  if (data.action) _params.value = clone(data.action.default_value_parse, true)
  if (data.title) _title.value = data.title
  _action.value = data.action
  _row.value = data.row
  _business.value = data.action?.business_id
  dialogVisible.value = true
  nextTick(() => {
    _edit.value = _edit_keys.includes(key)
    _key.value = key
  })
}

// const open = (option: { key: string, id: string; title: string }) => {
//   // _business.value = option.id
//   // title.value = option.title
//   // dialogVisible.value = true
//
// }

/**
 * 提交
 * onSave 必须是Promise
 */
const onSubmit = () => {
  if (_page.value) {
    if (_page.value.onSave) {
      _loading.value = true
      _page.value.onSave().finally(() => {
        _loading.value = false
      })
    }
  }
}

const onFetch = () => {
  dialogVisible.value = false
  emit('fetch')
}

const onClose = (isFetch?: boolean) => {
  dialogVisible.value = false
  if (isFetch) emit('fetch')
}

// 手动关闭时检查是否有修改等等操作
const handleClose = (done: () => void) => {
  const $vm = unref(_page)
  if ($vm && $vm.gridRef && $vm.gridRef.getInstance) {
    const { del, upd } = $vm.gridRef.getUpdateRows()
    if (del.length || upd.length) {
      ElMessageBox.confirm('编辑未保存，是否放弃编辑，关闭弹窗？')
        .then(() => {
          done()
        })
        .catch(() => {
          // catch error
        })
    } else {
      done()
    }
  } else {
    done()
  }
}

defineExpose({ open })
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    width="80%"
    append-to-body
    :close-on-click-modal="modal"
    :fullscreen="fullscreen"
    destroy-on-close
    :before-close="handleClose"
  >
    <template #header>
      <div class="flex align-center justify-between">
        <div v-if="_edit">
          <el-button type="primary" :icon="Edit" @click="onSubmit" :loading="_loading"
            >提交
          </el-button>
          <el-button @click="dialogVisible = false" :loading="_loading">关闭</el-button>
        </div>
        <span class="font16 mr10">{{ _title }}</span>
      </div>
    </template>
    <div style="height: 75vh" class="layout-container relative">
      <TemplateGrid
        v-if="_key === 'TemplateGrid' && _business"
        ref="_page"
        :box-shadow="false"
        :params="_params"
        v-model="_business"
        @close="onClose"
        @fetch="onFetch"
      />
      <TemplatePrint
        v-else-if="_key === 'TemplatePrint'"
        ref="_page"
        :_id="_id"
        :_row="_row"
        :default-params="params"
        :_action="_action"
        :_params="_params"
        :ui-form="uiForm"
        :dic-table="dicTable"
        @close="onClose"
        @fetch="onFetch"
      />
      <TemplateTableSelector
        v-else-if="_key === 'TableSelector'"
        ref="_page"
        :_id="_id"
        :_row="_row"
        :default-params="params"
        :_action="_action"
        :_params="_params"
        :ui-form="uiForm"
        :dic-table="dicTable"
        @close="onClose"
        @fetch="onFetch"
      />
      <TemplateFormContent
        v-else-if="_key === 'TemplateForm' && _business"
        ref="_page"
        v-model="_business"
        :params="_params"
        :default-params="params"
        @close="onClose"
        @fetch="onFetch"
      />
      <TemplateOvertime
        v-else-if="_key === 'TemplateOvertime'"
        ref="_page"
        insert
        :_id="_id"
        :_action="_action"
        :_params="_params"
        :default-params="params"
        @close="onClose"
        @fetch="onFetch"
      />
      <TemplateDeduction
        v-else-if="_key === 'TemplateDeduction'"
        ref="_page"
        insert
        :_id="_id"
        :_action="_action"
        :_params="_params"
        :default-params="params"
        @close="onClose"
        @fetch="onFetch"
      />
    </div>
  </el-dialog>
</template>
